/*setTimeout(function(){
    var aaa = api.frameName;
    var bbb = api.winName;
    if(aaa){
        api.toast({
            msg: aaa,
            duration: 3000,
            location: 'middle'
        });
    }
},1000)*/
// var rootPath = 'http://bit.liangzibiao.com';
// var rootPath = 'http://13.250.39.107';
var rootPath = 'http://47.75.114.114:8083';
/*云之讯*/
var accountSid = '5fcac41930826ab1c2003e393b36b40b';
var accountToken = '0503bb82836ff0198e5c5aeaa80eb91d';
var appId  = 'dd0462c94a5644d999cc696db509e534';
/*云之讯*/
/*微信*/
//wx9aab33c21fabe1a5
//b178189f2036e8f8a396cbac8e401fe3
// var apiKey = 'wx9aab33c21fabe1a5';
var wxAppId = 'wxf8cb61d452b2e35e';
var wxAppSecret = 'cd907b2265c5d751011143a9fe939de1';
/*微信*/
/*极光推送*/
var appKey = '3bf919710fa69cedbeb6a353';
var appSecret = 'd6d9f3caa584c87d19ae4239';
var pullArr = [
                'widget://image/refresh/1.png',
                'widget://image/refresh/2.png',
                'widget://image/refresh/3.png',
                'widget://image/refresh/4.png',
                'widget://image/refresh/5.png',
                'widget://image/refresh/6.png',
                'widget://image/refresh/7.png',
                ];
var loadArr = [
                'widget://image/refresh/1.png',
                'widget://image/refresh/2.png',
                'widget://image/refresh/3.png',
                'widget://image/refresh/4.png',
                'widget://image/refresh/5.png',
                'widget://image/refresh/6.png',
                'widget://image/refresh/7.png',
                ];
/*极光推送*/
function showError(code,msg) {
    api.toast({
        msg: msg,
        location:'middle'
    })
}
// 格式化视频封面图
function formatVideoImg (img) {
    if(!img) {
        return '../image/default.png';
    }
    if(img.indexOf('http') >= 0){
        return img;
    }else{
        return rootPath + img;
    }

};
//打开loading
l_id = 0;
function openLoading() {
    var UILoading = api.require('UILoading');
    UILoading.flower({
        mask : 'rgba(0,0,0,0)'
    },function(ret,err){
        l_id = ret.id
    });

}
//关闭loading
function closeLoading() {
    var uiloading = api.require('UILoading');
    uiloading.closeFlower({
        id: l_id
    });
}
//预加载图片，加载完毕后才显示图片
function setImg(_this) {
   $(_this).show();
   $(_this).prev().hide();
}
//预加载图片，加载完毕后才显示图片
function setObjImg(obj) {
   obj.show();
   obj.prev().hide();
}
/**
 * 登录成功的跳转
 * @param data 登录返回的数据
 */
 function successLogin(ret,toFrame,msg) {
    msg = msg?msg:'登录成功';
    $api.setStorage('shop_data', ret.data);
    api.toast({
        msg: msg,
        location:'middle'
    });
    api.sendEvent({
        name: 'loginEvent',
        extra: {
            user_data : ret.data
        }
    });
 }
//重新更新userstorage数据
function reSaveUser() {
    var user = $api.getStorage('user_data');
    api.ajax({
        url : rootPath + '/api/user/get_user_info?uid='+user.id+'&token='+user.token,
    },function(ret,err){
        if(ret) {
            if(ret.status == 200) {
                var new_user = ret.data;
                new_user.login_type = user.login_type;
                $api.setStorage('user_data',new_user);
                user = new_user;
            }
        }
    })
}

//显示用户头像
function showHeadImg() {
    var user = $api.getStorage('user_data');
    var user_head = $api.byId('user_head');
    if(!user.img ) {
        $api.attr(user_head,'src','../image/00-3-1.png');
    }else if(user.img.indexOf('http') >= 0) {
        $api.attr(user_head,'src',user.img);
    }else {
        $api.attr(user_head,'src',rootPath + user.img);
    }
}
//返回用户头像
function formatHeadImg(img) {
    if(!img) {
        return '../image/default.png';
    }else if(img.indexOf('http') >= 0) {
        return img;
    }else if(img.indexOf('local') > 0){
        return '..'+img;
    }else {
        return rootPath + img;
    }
}

//分享到微信
function shareWx() {
    var user = $api.getStorage('user_data');
    var invite = 'R-'+user.card_number;
    api.showProgress();
    setTimeout(function(){
        api.hideProgress();
    },3000)
    var wx = api.require('wx');
    wx.isInstalled(function(ret, err){
        if(ret.installed){
            wx.shareWebpage({
                apiKey: wxAppId,
                scene: 'session',
                title: '拉斐尔邀请注册，邀请码：'+invite,
                description: '快来注册吧',
                thumb: 'widget://image/share_logo.png',
                contentUrl: rootPath + '/home/index/share_register/card_number/'+user.card_number
            }, function(ret, err){
                if(ret.status){
                    api.toast({
                        msg:'分享成功',
                        location:'middle'
                    })
                }else{
                    api.toast({
                        msg:'分享失败',
                        location:'middle'
                    })
                }
            });
        }else{
            alert('请先安装微信客户端');
        }
    });
}

/**
 * 检查是否为手机
 * @param {[type]} text [要检测得手机号码]
 */
/*function isMobile (text) {
    if (text) {
        var _emp = /^\s*|\s*$/g;
        var _d = /^1[3578][013479]\d{8}$/g;
        var _l = /^1[34578][012456]\d{8}$/g;
        var _y = /^(134[012345678]\d{7}|1[34578][012356789]\d{8})$/g;
        text = text.replace(_emp, "");
            if (_d.test(text)) {
            return 3;
        } else if (_l.test(text)) {
            return 2;
        } else if (_y.test(text)) {
            return 1;
        }
        return 0;
    }
    return 0;
}*/

// 检测是否为马来西亚的手机
function isMobile (text) {
    if (text) {
        if(!isNaN(text)){
            return 1;
        }
        return 0;
    }
    return 0;
};


// 循环dot模板数据
function setDotData (data,id1,id2,isBool) {
    var listT = $api.byId(id1);
    var listTFn = doT.template(listT.text);
    var html = listTFn(data);
    var list = $api.byId(id2);
    $api.html(list, html);
    if(true == isBool){
        api.parseTapmode();
    }
};

// 插入dot模板数据 type = true 是从前面增加，否则是从后面添加
function appendDotData (data,id1,id2,isBool,type) {
    var listT = $api.byId(id1);
    var listTFn = doT.template(listT.text);
    var html = listTFn(data);
    var list = $api.byId(id2);
    if(true == type){
        $api.prepend(list,html);
    }else{
        $api.append(list,html);
    }
    if(true == isBool){
        api.parseTapmode();
    }
};

// 把uploads文件夹替换成有路径的uploads
function replaceAllUploads(str){
if(str!=null)
    str = str.replace(/\/Uploads\//g,rootPath + '/Uploads/')
    return str;
}

// 显示无内容时默认加载图
function showDefaultNoWeb (_id,_callback) {
    api.toast({
        msg: '网络异常,请检查网络配置',
        location: 'middle'
    });
    setTimeout(function(){
    $api.html($api.byId(_id), '<div id="no_network"><img style="margin:0 auto;display: block;margin-top: 100px;" src="../image/network.png"><p style="text-align: center;color: #3f3f3f;font-size: 17px;line-height: 100px;"><span style="line-height: 30px;background: #1ebcd1;color: white;padding: 4px 8px;border-radius: 3px;visibility: hidden;" tapmode onclick="reloadAllNoWeb(' + _callback + ');">重新加载</span></p></div>');
        // $api.html(adContent, '<div class="no_content_img"><img src="..//image/temp/detail_default.png" alt=""></div>');
    },200);
    setTimeout(function(){
        $api.css($api.dom(no_network, 'span'), 'visibility:visible;');
        closeLoading();
    },210);
}

// 无网时重新加载更多
function reloadAllNoWeb(_callback) {
    var connectionType = api.connectionType;
    if('none' != connectionType){
        // $api.html(associationContent, '');
        $api.remove(no_network);
    }
    eval(_callback);
}

//接收socket
function accept_socket(msg_uid) {
    var socket = io('http://workerman.vsonter.com:2120');
    // 连接服务端
    // 连接后登录
    socket.on('connect', function(){
        socket.emit('login', msg_uid);
    });
    // 后端推送来消息时
    socket.on('new_msg', function(receive_data){
        if (receive_data.flag == "bit_shop") {
            delete(receive_data.current_web_host);
            delete(receive_data.msg_sender_type);
            receive_fn(receive_data);
        }
    });
}


// 检测网络状态
function checkNetWork(_callback) {
    var connectionType = api.connectionType;
    if('none' == connectionType){
        api.toast({
            msg: '网络异常,请检查网络配置',
            location:'middle'
        });
    }else{
        _callback();
    }
}

function fnGetArticle(title,mark) {
    api.openWin({
        name: 'about_us',
        url: 'about_us.html',
        pageParam : {
            title: title,
            mark : mark
        }
    });
}

// news页面数据获取共用方法，type= ['Top News','Topic','Politics','Economy','Culture','Travel','Style','Tech','Photo','Video','China','World','Sports','ODD'];t=0是首次获取 t=1是下拉刷新,t=2是上拉加载更多...
function getNewsInitData (type,t) {
    openLoading();
    api.ajax({
        url: rootPath + '/api/news/get_news',
        method: 'get',
        cache:true,
        data: {
            values: {
                type: type,
                device_id: api.deviceId,
            },
        }
    }, function(ret, err) {
        if (ret) {
            if(ret.status == 200){
                $(".without_data").hide();
                if(t == 2){
                    appendDotData(ret.data,'newsL','newsC',true); // 第五个参数为空，从后面添加
                }else{
                    appendDotData(ret.data,'newsL','newsC',true,true); // 第五个参数true 是从前面增加
                }
            }else if(ret.status ==201){
                if(t == 0){
                    // 首次获取就没有数据
                    $("#newsC").html('');
                    $(".without_data").show();
                }else{
                    // 下拉或上拉加载时没有数据
                }
            }
        } else {

        }
        if(t == 1){
            // 是下拉刷新的，要收回
            api.refreshHeaderLoadDone();
            var total = ret.data.length?ret.data.length:0;
            $(".total").html(total);
            $(".new_fetch").show();
            setTimeout(function(){
                $(".new_fetch").hide();
            },2000);
        }
        if(t == 2){
            // 是上拉加载更多，要隐藏
            $(".loading").hide();
            /*setTimeout(function(){
                $(".loading").hide();
            },1000);*/
        }
        can_get = true;
        closeLoading();
    });
};

// news页面下拉刷新和上拉加载的共用方法type= ['Top News','Topic','Politics','Economy','Culture','Travel','Style','Tech','Photo','Video','China','World','Sports','ODD'];t=0是首次获取 t=1是下拉刷新,t=2是上拉加载更多...
function setNewsHeaderInfo (type) {
    //下拉刷新
    api.setCustomRefreshHeaderInfo({
        bgColor: '#fff',
        loadAnimInterval:60,
        image: {
           pull: pullArr,
           load: loadArr
        }
    }, function(ret, err) {
        getNewsInitData(type,1);
    });
    /*// 下拉加载最新数据
    api.setRefreshHeaderInfo({
        bgColor: '#fff',
        textColor: '#ccc',
        textDown: 'Pull To Refresh',
        textUp: 'Release To Refresh',
        textLoading: 'Refreshing',
        // textTime: 'Latest Update: 12:32:48',
        showTime: true
    }, function(ret, err) {
        getNewsInitData(type,1);
    });*/

};

function setNewsListener (type) {
    // 上拉加载
    api.addEventListener({
        name:'scrolltobottom',
        extra:{
            threshold:0            //设置距离底部多少距离时触发，默认值为0，数字类型
        }
    }, function(ret, err){
        if(can_get == true){
            can_get = false;
            $(".loading").show();
            getNewsInitData(type,2);
        }
    });

};

function fnOpenSeller(id) {
    api.openWin({
        name: 'seller',
        url: './seller.html',
        pageParam: {
            id: id
        }
    });
}
